package com.MetaverseMaker.UniverseFarm.controller;


import com.MetaverseMaker.UniverseFarm.dto.MyMessage;
import com.MetaverseMaker.UniverseFarm.entity.OrderInfo;
import com.MetaverseMaker.UniverseFarm.entity.OrderInfoVO;
import com.MetaverseMaker.UniverseFarm.entity.SoilInfo;
import com.MetaverseMaker.UniverseFarm.entity.UserInfo;
import com.MetaverseMaker.UniverseFarm.service.ISoilInfoService;
import com.MetaverseMaker.UniverseFarm.service.IUserInfoService;
import com.MetaverseMaker.UniverseFarm.service.impl.OrderInfoServiceImpl;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * @Auther: wanghuiqian
 * @Date: 2021/11/21 - 11 - 21 - 21:38
 * @Description: controller
 * @version: 1.0
 */




@Controller
public class LoginController {
    private IUserInfoService iUserInfoService;
    @Resource
    private ISoilInfoService iSoilInfoService;
    @Resource
    private OrderInfoServiceImpl orderInfoService;
    public IUserInfoService getiUserInfoService() {
        return iUserInfoService;
    }
    @Autowired
    public void setiUserInfoService(IUserInfoService iUserInfoService) {
        this.iUserInfoService = iUserInfoService;
    }
    @RequestMapping("/Login")
    @ResponseBody       //表示 直接返回数据   json格式的数据
    public MyMessage testLogin(String name, String pwd, HttpSession session) throws Exception {
        UserInfo userInfo=new UserInfo();
        System.out.println(name);
        System.out.println(pwd);
        userInfo.setUserAccount(name);
        userInfo.setUserPassword(pwd);
        System.out.println(userInfo.getUserAccount());
        System.out.println(userInfo.getUserPassword());
        UserInfo userInfo1=iUserInfoService.find(name,pwd);
//        User user=userSerivce.checkLogin(name,pwd);
        MyMessage my=new MyMessage();
        if(userInfo1==null){
            //当前用户名或者密码错误
            my.setMsg("用户名或者密码错误！");
            my.setFlag(0);
        }else{
            if(userInfo1.getUserStatus()==1){
                //当前用户被禁用
                my.setMsg("当前用户被禁用！");
                my.setFlag(1);
            }else{
                //当前用户可以使用
                my.setMsg("登录成功");
                my.setFlag(2);
                //将当前用户保存在session中
                session.setAttribute("loginuser",userInfo1);
            }
        }
        return my;
    }
    @RequestMapping("/isLogin")
    @ResponseBody   //表示 直接返回数据   json格式的数据
    public  MyMessage  isLogin(HttpSession session){
        System.out.println(session.getId());
        MyMessage msg=new MyMessage();
        //获取session的登录用户
        System.out.println(session.getAttribute("loginuser"));
        if(session.getAttribute("loginuser")==null){
            //未登录
            msg.setFlag(0);
        }else{
            //已登录
            msg.setFlag(1);
            msg.setData(session.getAttribute("loginuser"));
        }
        return msg;
    }
    @RequestMapping("/loginOut")
    @ResponseBody
    public MyMessage  loginOut(HttpSession session){
        session.invalidate();  //让session失效
        MyMessage msg=new MyMessage();
        msg.setMsg("注销成功");
        return msg;
    }

    @RequestMapping("/register")
    @ResponseBody
    public MyMessage register(String account,String pwd,String name,String phone) throws Exception {
//        boolean flag= userSerivce.register(name,pwd);
        UserInfo userInfo=iUserInfoService.find(account,pwd);
        boolean flag=true;
        if(userInfo!=null||account==null||pwd==null||name==null)
            flag=false;
        MyMessage msg=new MyMessage();
        if(flag){
            //注册成功
            UserInfo userInfo1=new UserInfo();
            userInfo1.setUserAccount(account);
            userInfo1.setUserName(name);
            userInfo1.setUserPassword(pwd);
            userInfo1.setUserIntegral(0.00);
            userInfo1.setUserStatus(0);
            userInfo1.setUserPhone(phone);
            boolean f=iUserInfoService.saveUser(userInfo1);
            if(f){
                msg.setMsg("注册成功");
                msg.setFlag(1);
//                SoilInfo soilInfo=new SoilInfo();
//                soilInfo.setSoilName(userInfo1.getUserName()+"的农场");
//                soilInfo.setSoilFruit("农场");
//                soilInfo.setSoilPhoto("");


            }
            else
            {
                //注册失败
                msg.setMsg("注册失败");
                msg.setFlag(0);
            }
        }else{
            //注册失败
            msg.setMsg("用户名已存在或输入空字段");
            msg.setFlag(0);
        }
        System.out.println("register");
        return msg;
    }

    @RequestMapping("/getLoginUser")
    @ResponseBody
    public MyMessage  getLoginUser(HttpSession session) throws Exception {
        //从会话中获取登录用户
        UserInfo userInfo1= (UserInfo) session.getAttribute("loginuser");
        UserInfo userInfo=iUserInfoService.findUserById(userInfo1.getUserId());
        MyMessage msg=new MyMessage();
        if(userInfo==null){
            //说明会话已经结束，重新登录
            msg.setFlag(0);
            msg.setMsg("当前登录状态已经失效，请重新登录！");
        }else{
            msg.setFlag(1);
            msg.setData(userInfo);
        }
        return msg;
    }

    @RequestMapping("/checkRechargeUser")
    @ResponseBody
    public MyMessage  checkRechargeUser(String userAccount,String userPhone,double recharges,HttpSession session) throws Exception {
        //从会话中获取登录用户
        MyMessage msg=new MyMessage();
        UserInfo userInfo=iUserInfoService.findUserByUserAccount(userAccount);
        if(userInfo==null){
            msg.setFlag(0);
            msg.setMsg("充值失败！！该用户不存在！！");
        }else{
            if(userInfo.getUserPhone().equals(userPhone)){

                userInfo.setUserIntegral(userInfo.getUserIntegral()+(recharges*13));
                boolean f=iUserInfoService.updateUser(userInfo);
                if(f){
                    msg.setFlag(1);
                    msg.setMsg("充值成功！！该账户余额为："+userInfo.getUserIntegral());
                }else {
                    msg.setFlag(0);
                    msg.setMsg("充值失败！！不知道为嘛充不进去！！");
                }
            }else{
                msg.setFlag(0);
                msg.setMsg("充值失败！！账号与号码不对应！！");
            }
        }



        return msg;
    }
//Withdrawal
@RequestMapping("/checkWithdrawalUser")
@ResponseBody
public MyMessage  checkWithdrawalUser(String userAccount,String userPhone,double withdrawal,HttpSession session) throws Exception {
    //从会话中获取登录用户
    MyMessage msg=new MyMessage();
    UserInfo userInfo=iUserInfoService.findUserByUserAccount(userAccount);
    if(userInfo.getUserPhone().equals(userPhone)){

        userInfo.setUserIntegral(userInfo.getUserIntegral()-withdrawal);
        boolean f=iUserInfoService.updateUser(userInfo);
        if(f){
            msg.setFlag(1);
            msg.setMsg("提现成功！！");
        }else {
            msg.setFlag(0);
            msg.setMsg("提现失败！！提不出去！！");
        }
    }else{
        msg.setFlag(0);
        msg.setMsg("提现失败！！号码或密码错误！！");
    }


    return msg;
}
    @RequestMapping("/updateUserInfo")
    @ResponseBody
    public MyMessage  updateUserInfo(String userRname,String phone,String address,HttpSession session) throws Exception {
        MyMessage my=new MyMessage();
        //从会话中获取登录用户
        UserInfo userInfo= (UserInfo) session.getAttribute("loginuser");
//        System.out.println(userRname);
//        System.out.println(address);
//        System.out.println(phone);
        userInfo.setUserName(userRname);
        userInfo.setUserAddressed(address);
        userInfo.setUserPhone(phone);
//        System.out.println(userInfo.getUserName());
//        System.out.println(userInfo.getUserPhone());
//        System.out.println(userInfo.getUserAddressed());

        if(iUserInfoService.updateUser(userInfo)){
            //修改成功
            my.setFlag(1);
            my.setMsg("修改成功");
            //重新刷新session    根据userid 查询用户
            UserInfo user=iUserInfoService.findUserById(userInfo.getUserId());
            session.setAttribute("loginuser",user);

        }else{
            //修改失败
            my.setFlag(0);
            my.setMsg("修改失败");
        }

        return my;
    }

    @RequestMapping("/uploadUserAvatar")
    @ResponseBody
    public MyMessage  uploadUserAvatar(@RequestParam MultipartFile file, HttpServletRequest request, HttpSession session) throws Exception {
        /*// 对字节数组字符串进行Base64解码并生成图片
        String strImge = "";
        GenerateImage(strImge, "D:\\11.jpg");*/


        System.out.println(session.getId());
        //获取上传图片的原名称
        String fileName=file.getOriginalFilename();
        System.out.println(fileName);
        //获取要保存的目录
        String path =request.getServletContext().getRealPath("static/picture/avatar");
        System.out.println(path);
        //上传的文件最好是要重命名，这样才能保存不会因为上传相同名称的文件而报错
        fileName=System.currentTimeMillis()+"_"+fileName;
        System.out.println(fileName);
        //构造file对象
        File myfile=new File(path+"/"+fileName);
        boolean flag=false;
        try {
            //将前段的文件复制到后端服务器中
            FileUtils.copyInputStreamToFile(file.getInputStream(),myfile);
            flag=true;
            System.out.println("上传成功");
            //上传成功后还需要更新数据库中的用户logo
            UserInfo user= (UserInfo) session.getAttribute("loginuser");
            user.setUserPhoto(fileName);
            boolean flag2=iUserInfoService.updateUser(user);
            if(flag2){
//                user.setUser_logo(fileName);
                System.out.println("更新头像成功！");
            }
        }catch (Exception e){
        }
        MyMessage my=new MyMessage();
        if(flag){
            //上传成功
            my.setFlag(1);
            /*my.setData(fileName);*/
            UserInfo user2= (UserInfo) session.getAttribute("loginuser");
            UserInfo user3=iUserInfoService.findUserById(user2.getUserId());
            session.setAttribute("loginuser",user3);
        }else{
            //上传失败
            my.setFlag(0);
        }
        return my;
    }
    // 对字节数组字符串进行Base64解码并生成图片
    public static boolean GenerateImage(String imgStr, String imgFilePath) {
        if (imgStr == null) // 图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
//    @RequestMapping("/getUser")
//    @ResponseBody
//    public void getUser()
//    {
//
//    }
    @RequestMapping("/getOrder")
    @ResponseBody
    public MyMessage getOrder(HttpSession session) throws Exception {
        List<OrderInfo> list=orderInfoService.queryAllOrder();
//        List<OrderInfoVO> list=orderInfoService.queryAllOrders();
        MyMessage myMessage=new MyMessage();

            UserInfo userInfo=(UserInfo) session.getAttribute("loginuser");
            if(userInfo.getUserStatus()!=2)
            {
                myMessage.setFlag(0);
                myMessage.setMsg("您不是管理员");
                return myMessage;
            }
            else
            {
                myMessage.setFlag(1);
                myMessage.setData(list);
                return myMessage;
            }

    }

    @RequestMapping("/getUser")
    @ResponseBody
    public MyMessage getUser(HttpSession session) throws Exception {
        List<UserInfo> list=iUserInfoService.findAll();
        System.out.println("userList="+list.size());
//        List<OrderInfoVO> list=orderInfoService.queryAllOrders();
        MyMessage myMessage=new MyMessage();

            UserInfo userInfo=(UserInfo) session.getAttribute("loginuser");
            if(userInfo.getUserStatus()!=2)
            {
                myMessage.setFlag(0);
                myMessage.setMsg("您不是管理员");
                return myMessage;
            }
            else
            {
                myMessage.setFlag(1);
                myMessage.setData(list);
                return myMessage;
            }

    }

    @RequestMapping("/changeUserStatus")
    @ResponseBody
    public MyMessage changeUserStatus(Integer userId,HttpSession session) throws Exception {
        UserInfo userInfo=iUserInfoService.findUserById(userId);
        if(userInfo.getUserStatus()==0){
            userInfo.setUserStatus(1);
        }else if(userInfo.getUserStatus()==1){
            userInfo.setUserStatus(0);
        }
        MyMessage myMessage=new MyMessage();

        UserInfo userInfo2=(UserInfo) session.getAttribute("loginuser");


            if(userInfo2.getUserStatus()!=2)
            {
                myMessage.setFlag(0);
                myMessage.setMsg("您不是管理员");
                return myMessage;
            }
            else
            {
                boolean f=iUserInfoService.updateUser(userInfo);
                if(f){
                    myMessage.setFlag(1);
                    myMessage.setMsg("状态更改成功！");
                    return myMessage;
                }
                else{
                    myMessage.setFlag(0);
                    myMessage.setMsg("状态更改失败！");
                    return myMessage;
                }
            }

    }
    @RequestMapping("/changeOrderStatus")
    @ResponseBody
    public MyMessage changeOrderStatus(Integer orderId,HttpSession session) throws Exception {
        MyMessage myMessage=new MyMessage();
        OrderInfo orderInfo=orderInfoService.queryById(orderId);
        if(orderInfo.getOrderStatus().equals("已配送")){
            myMessage.setFlag(0);
            myMessage.setMsg("该订单已配送完毕");
            return myMessage;
        }
        else {
            UserInfo userInfo2 = (UserInfo) session.getAttribute("loginuser");

                if (userInfo2.getUserStatus() != 2) {
                    myMessage.setFlag(0);
                    myMessage.setMsg("您不是管理员");
                    return myMessage;
                } else {
                    orderInfoService.updateOrder(orderId, "已配送");

                    myMessage.setFlag(1);
                    myMessage.setMsg("状态更改成功！");
                    return myMessage;
                }

        }
    }
}
